<?php

require './config.php';

use Thenbsp\Wechat\OAuth\Client;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

$client = new Client(APPID, APPSECRET);
$client->setScope('snsapi_userinfo');
$client->setRedirectUri(URL.'/wechat');

/**
 * 当前请求对象
 */
$request = Request::createFromGlobals();

/**
 * 获取授权地址
 */
if (!$request->query->has('authorization_code')) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_OK,
        'data' => $client->getAuthorizeUrl()
    ]);
    $response->send();
}

$_accessToken       = $request->query->get('access_token');
$_authorizationCode = $request->query->get('authorization_code');

/**
 * 根据 code 换取微信 access_token
 */
try {
    $accessToken = $client->getAccessToken($_authorizationCode);
} catch (\Exception $e) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR,
        'data' => $e->getMessage()
    ]);
    $response->send();
}

/**
 * 根据用户 access_token 查找用户
 */
$userinfo = getUserByAccessToken($_accessToken);

if (!$userinfo) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR,
        'data' => 'Invalid AccessToken'
    ]);
    $response->send();
}

$response = new JsonResponse([
    'code' => JsonResponse::HTTP_OK,
    'data' => $userinfo
]);
$response->send();

/**
 * 用户已绑定过微信了
 */
if (!empty($userinfo['openid'])) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_OK,
        'data' => []
    ]);
    $response->send();
}

/**
 * 更新用户
 */
$rowCount = setOpenidByUesrid($userinfo['id'], $accessToken['openid']);

$response = new JsonResponse([
    'code' => JsonResponse::HTTP_OK,
    'data' => $rowCount
]);
$response->send();
